<template>
  <div class="permission-node" :style="{ marginLeft: isRoot ? '0px' : depth * 20 + 'px' }">

    <!-- 节点标题 -->
    <div
        v-if="hasChildren"
        :class="['node-header', { 'root-title': isRoot, 'clickable': true }]"
        @click="toggleExpand"
    >
      <span>{{ isExpanded ? '▼' : '▶' }}</span>
      <strong>{{ item.pname }}</strong>

      <!-- 操作按钮 -->
      <span class="action-buttons" @click.stop>
        <el-button type="primary" text icon="Plus" @click="emitAdd(item.id)" />
        <el-button type="warning" text icon="Edit" @click="emitEdit(item.id,item.pname,item.code)" />
        <el-button type="danger" text icon="Delete" @click="emitDelete(item.id)" />
      </span>
    </div>

    <div v-else class="leaf-item">
      <div class="leaf-content">
        <el-button type="text" @click="handleClick(item.pname)">
          {{ item.pname }}
        </el-button>

        <!-- 叶子节点操作按钮 -->
        <span class="action-buttons" @click.stop>
          <el-button type="primary" text icon="Plus" @click="emitAdd(item.id)" />
          <el-button type="warning" text icon="Edit" @click="emitEdit(item.id,item.pname,item.code)" />
          <el-button type="danger" text icon="Delete" @click="emitDelete(item.id)" />
        </span>
      </div>
    </div>

    <!-- 展开区域：先显示无子节点的（横向），再显示有子节点的（纵向） -->
    <div v-show="isExpanded && hasChildren" class="children-container">

      <!-- 第一部分：没有孙子节点的子节点（即叶子节点）—— 横向显示 -->
      <div v-if="withoutGrandchildren.length > 0" class="horizontal-section">
        <div v-for="child in withoutGrandchildren" :key="child.id" class="inline-item">
          <el-button type="text" @click="handleClick(child.pname)">
            {{ child.pname }}
          </el-button>
          <!-- 子节点操作按钮 -->
          <span class="action-buttons" @click.stop>
            <el-button type="primary" text icon="Plus" @click="emitAdd(child.id)" />
            <el-button type="warning" text icon="Edit" @click="emitEdit(child.id,child.pname,child.code)" />
            <el-button type="danger" text icon="Delete" @click="emitDelete(child.id)" />
          </span>
        </div>
      </div>

      <!-- 第二部分：有孙子节点的子节点 —— 竖向显示 -->
      <div v-for="child in withGrandchildren" :key="child.id" class="vertical-section">
        <PermissionItem
            :item="child"
            :depth="depth + 1"
            :visited-ids="[...visitedIds, item.id]"
            @action="handleClick"
        />
      </div>

    </div>

    <!-- 弹窗表单 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'edit' ? '编辑权限' : '新增权限'"
        width="400px"
    >
      <el-form :model="dialogForm" label-width="80px" :rules="rules" ref="formRef">
        <el-form-item prop="pname" label="权限名">
          <el-input v-model="dialogForm.pname" placeholder="请输入权限名" />
        </el-form-item>
        <el-form-item prop="code" label="权限码">
          <el-input v-model="dialogForm.code" placeholder="请输入权限码" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button @click="submit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'
import axios from "axios";
  import { ElMessage, ElMessageBox } from "element-plus";

  const props = defineProps({
  item: Object,
  depth: { type: Number, default: 0 },
visitedIds: { type: Array, default: () => [] }
})

const emit = defineEmits(['action'])

  // 点击权限名称触发事件
const handleClick = (pname) => {
emit('action', pname)
}

  // 弹窗相关
  const dialogVisible = ref(false)
  const dialogType = ref('add')
  const dialogForm = ref({ pname: '', code: '' })
const formRef = ref(null)
const rules = {
  pname: [{ required: true, message: '请输入权限名', trigger: 'blur' }],
code: [{ required: true, message: '请输入权限码', trigger: 'blur' }]
}
  const opd = ref(null)

      // 新增权限
  const emitAdd = (id) => {
  dialogType.value = 'add'
dialogForm.value = { pname: '', code: '' }
  dialogVisible.value = true
opd.value = id
}

  // 编辑权限
  const emitEdit = (id,pname,code) => {
  dialogType.value = 'edit'
dialogForm.value = {
  pname: pname || '',
  code: code || ''
}
  dialogVisible.value = true
opd.value = id
}

  // 提交权限
  const submit = () => {
  if (dialogType.value === "add") {
  axios.post(`/permission/addNewPermission/${opd.value}`, dialogForm.value).then(() => {
  ElMessage.success("新增权限成功")
dialogVisible.value = false
emit('action', { type: 'add', item: props.item })
})
} else if (dialogType.value === "edit") {
  axios.post(`/permission/editPermission/${opd.value}`, dialogForm.value).then(() => {
  ElMessage.success("修改权限成功")
dialogVisible.value = false
emit('action', { type: 'edit', item: props.item })
})
}
}

  // 删除权限
  const emitDelete = (id) => {
  ElMessageBox.confirm(
'此操作将永久删除该权限及其所有子权限，是否继续？',
'提示',
{
  confirmButtonText: '确定',
  cancelButtonText: '取消',
  type: 'warning'
}
).then(() => {
  axios.delete(`/permission/deletePermission/${id}`)
.then(() => {
  ElMessage.success('删除权限成功')
emit('action', { type: 'delete', item: props.item })
})
.catch(() => {
  ElMessage.error('删除失败')
})
}).catch(() => {
  ElMessage.info('已取消删除')
})
}

  // 判断是否有子节点
  const hasChildren = computed(() =>
  props.item.children && props.item.children.length > 0
)

  // 判断子节点中哪些有孙子节点
const withGrandchildren = computed(() =>
props.item.children?.filter(child => child.children && child.children.length > 0) || []
)

  // 判断子节点中哪些没有孙子节点
const withoutGrandchildren = computed(() =>
props.item.children?.filter(child => !child.children || child.children.length === 0) || []
)

  // 是否为根节点
const isRoot = computed(() => props.item.parentId == 0)

  // 控制展开/收起状态
const isExpanded = ref(true)
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
}
</script>

<style scoped>
.leaf-content {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  position: relative; /* 为按钮绝对定位提供锚点 */
}

.action-buttons {
  display: inline-flex;
  gap: 4px;
  visibility: hidden;
  vertical-align: middle;
}

.node-header:hover .action-buttons,
.leaf-item:hover .action-buttons,
.inline-item:hover .action-buttons {
  visibility: visible;
}

.leaf-content:hover > .action-buttons {
  visibility: visible;
}
.permission-node {
  margin-top: 8px;
}

.node-header {
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: center;
  gap: 6px;
  user-select: none;
  width: 100%;
  box-sizing: border-box;
}

.clickable {
  cursor: pointer;
}

.root-title {
  background-color: #d9eaff;
  color: #409eff;
  padding: 8px 12px;
  border-radius: 6px;
  margin-bottom: 10px;
  font-size: 16px;
}

.leaf-item {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  margin-left: 20px;
}

.buttons-container {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 8px;
  align-items: center;
}

.permission-item {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.el-button {
  font-size: 13px;
  padding: 4px 10px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.el-button:hover {
  background-color: #e6f0ff;
  border-color: #409eff;
  color: #409eff;
}

.action-buttons {
  display: inline-flex;
  gap: 4px;
  visibility: hidden;
  vertical-align: middle;
}

.permission-item:hover > .action-buttons,
.node-header:hover > .action-buttons,
.leaf-item:hover > .action-buttons {
  visibility: visible;
}

/* 竖向排列的子模块 */
.vertical-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 12px;
  padding: 6px 12px;
  background-color: #f9f9f9;
  border-left: 3px solid #e4e7ed;
}

/* 横向排列的操作权限 */
.horizontal-section {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
  padding: 6px 12px;
  background-color: #fcfcfc;
  border-top: 1px dashed #e4e7ed;
}

.inline-item {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  white-space: nowrap;
}
</style>